package com.meichis.yndms.ui.activity;


import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.meichis.mcsappframework.encrypt.AESProvider;
import com.meichis.mcsappframework.utils.AndroidEditUtil;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.FillModeRcAdapterNew;
import com.meichis.yndms.adapter.SpacesItemDecoration;
import com.meichis.yndms.common.CameraView;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.common.PictureUtils;
import com.meichis.yndms.databinding.ActivityVstFreequestionnaireOrderBinding;
import com.meichis.yndms.model.DicDataItem;
import com.meichis.yndms.model.InspectResult;
import com.meichis.yndms.model.InspectResult_Detail;
import com.meichis.yndms.model.InspectTemplate;
import com.meichis.yndms.model.InspectTemplate_Item;
import com.meichis.yndms.model.Picture;
import com.meichis.yndms.model.UserInfo;
import com.meichis.yndms.model.VisitWorkItem;
import com.meichis.yndms.room.AppDatabase;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.VST_FreeQuestionnaireVm;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @author : create by  szh
 * @date : 2022/11/15 11:16
 * @desc :顺序
 */

public class VST_FreeQuestionnaireOrderActivity extends BaseActivity {


    private VisitWorkItem item;

    ActivityVstFreequestionnaireOrderBinding binding;
    private FillModeRcAdapterNew fillModeRcAdapter;

    private InspectTemplate inspectTemplate;
    private ArrayList<DicDataItem> dicDataItems;
    private int position = 0;

    private String workGuid, code;
    private UserInfo userInfo;

    private String curDate = "1900-01-01";
    private VST_FreeQuestionnaireVm vm;
    private ArrayList<Integer> questionIds;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_vst_freequestionnaire_order);
        vm = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(VST_FreeQuestionnaireVm.class);

        binding.setClick(new ClickEvent());
        AndroidEditUtil.assistActivity(this);
    }

    @Override
    protected void init() {
        binding.navigation.txtTitle.setText("问卷填写");
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        inspectTemplate = (InspectTemplate) getIntent().getSerializableExtra("question");

        curDate = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
        userInfo = (UserInfo) util.getObjectValue(SharePreferenceUtil.PREFERENCES_USERINFO);
        workGuid = getIntent().getStringExtra(MCode.VISITGUID);
        code = getIntent().getStringExtra(MCode.CODE);
        questionIds = (ArrayList<Integer>) getIntent().getSerializableExtra("questionIds");
        dicDataItems = inspectTemplate.getDim2KeyItems();
        if (dicDataItems.size() == 0) {
            dicDataItems.add(new DicDataItem());
        }
        vm.getQuestionIds().setValue(questionIds);
        fillModeRcAdapter = new FillModeRcAdapterNew(this, inspectTemplate.getItems());

        binding.rc.setLayoutManager(new LinearLayoutManager(this));
        binding.rc.addItemDecoration(new SpacesItemDecoration(0));
        binding.rc.setAdapter(fillModeRcAdapter);

        vm.getWorkItem(workGuid, code);
        addObserver();

    }

    private void addObserver() {
        vm.getItemData().observe(this, new Observer<VisitWorkItem>() {
            @Override
            public void onChanged(VisitWorkItem visitWorkItem) {
                if (visitWorkItem != null) {
                    item = visitWorkItem;
                    item2dic();
                    result2temp();
                    fillModeRcAdapter.notifyDataSetChanged();
                }
            }
        });
        vm.getSaveSuccess().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    MessageTools.showShortToast("保存成功");
                    close();
                }
            }
        });
        vm.getDeleteSuccess().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    close();
                }
            }
        });
    }


    /**
     * 填充item
     */
    private void item2dic() {
        InspectResult result;
        InspectResult_Detail detail;

        for (DicDataItem dic : dicDataItems) {
            result = null;
            for (InspectResult inspectResult : item.getInspectResults()) {
                if (inspectResult.getItems().get(0).getDim2KeyID() == dic.getID() && inspectResult.getInspectTemplate() == inspectTemplate.getID()) {
                    result = inspectResult;
                    break;
                }
            }
            if (result != null) {
                dic.setResult(result);
                continue;
            }
            result = new InspectResult();
            result.setInspectTemplate(inspectTemplate.getID());

            for (InspectTemplate_Item ititem : inspectTemplate.getItems()) {
                detail = new InspectResult_Detail();
                detail.setInspectItem(ititem.getItem().getID());
                detail.setInspectItemName(ititem.getItem().getName());
                detail.setIsMustFill(ititem.getIsMustFill());
                detail.setDim2KeyID(dic.getID());
                detail.setDim2KeyValue(dic.getValue());
                detail.setDim2KeyText(dic.getName());
                detail.setFillMode(ititem.getItem().getFillMode());
                detail.setRemark(ititem.getRemark());
                detail.setNeedExtRemark(ititem.getItem().getNeedExtRemark());
                result.getItems().add(detail);
            }
            dic.setResult(result);
        }
    }

    /**
     * 取结果填充到模板中
     */
    private void result2temp() {
        for (InspectTemplate_Item inspectTemplate_item : inspectTemplate.getItems()) {
            inspectTemplate_item.setProcessCode(code);
            for (InspectResult_Detail detail : dicDataItems.get(position).getResult().getItems()) {
                if (detail.getInspectItem() == inspectTemplate_item.getItem().getID()) {
                    switch (detail.getFillMode()) {
                        case 9:
                            if (inspectTemplate_item.getFillName() != null && detail.getFillName() != null)
                                inspectTemplate_item.setFillName(inspectTemplate_item.getFillName()
                                        + (inspectTemplate_item.getFillName().length() > 0 ? "|" + detail.getFillName() : detail.getFillName()));
                            break;
                        default:
                            inspectTemplate_item.setFillName(detail.getFillName());
                            break;
                    }
                    inspectTemplate_item.setFillValue(detail.getFillValue());
                    inspectTemplate_item.setRemark(detail.getRemark());
                }
            }
        }
    }

    public class ClickEvent {

        public void submit() {
            item.setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
            temp2result();
            dic2item();
            AppDatabase.getInstance().visitWorkItemDao().insert(item);
            vm.saveResult(inspectTemplate.getDim2KeyMode(), inspectTemplate.getID());
        }

        /**
         * 模板保存到结果中
         */
        private void temp2result() {
            for (InspectTemplate_Item inspectTemplate_item : inspectTemplate.getItems()) {
                for (int i = 0; i < dicDataItems.get(position).getResult().getItems().size(); i++) {
                    if (dicDataItems.get(position).getResult().getItems().get(i).getInspectItem() == inspectTemplate_item.getItem().getID()) {
                        switch (dicDataItems.get(position).getResult().getItems().get(i).getFillMode()) {
                            case 9:
                                dicDataItems.get(position).getResult().getItems().get(i).setFillName(inspectTemplate_item.getFillName());
                                dicDataItems.get(position).getResult().getItems().get(i).setFillValue(inspectTemplate_item.getFillValue());
                                break;
                            default:
                                dicDataItems.get(position).getResult().getItems().get(i).setFillName(inspectTemplate_item.getFillName());
                                dicDataItems.get(position).getResult().getItems().get(i).setFillValue(inspectTemplate_item.getFillValue());
                                break;
                        }

                        dicDataItems.get(position).getResult().getItems().get(i).setRemark(inspectTemplate_item.getRemark());
                    }
                }
            }
        }

        /**
         * 填写完成保存成item
         */
        private void dic2item() {
            List<Integer> InspectTemplateList = new ArrayList<>();
            if (item.getInspectResults() != null && item.getInspectResults().size() > 0) {
                for (InspectResult inspectResult : item.getInspectResults()) {
                    int inspectTemplate = inspectResult.getInspectTemplate();
                    InspectTemplateList.add(inspectTemplate);
                }
            }
            InspectResult result;
            for (DicDataItem dic : dicDataItems) {
                result = dic.getResult();
                if (item.getInspectResults() == null || item.getInspectResults().size() == 0) {
                    item.getInspectResults().add(result);
                } else {
                    if (InspectTemplateList.contains(inspectTemplate.getID())) {
                        int index = InspectTemplateList.indexOf(inspectTemplate.getID());
                        InspectResult inspectResult = item.getInspectResults().get(index);
                        inspectResult = result;
                    } else {
                        item.getInspectResults().add(result);
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        MessageTools.ShowmessageDialog(this, "是否清除填写记录？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                vm.delete(inspectTemplate.getID());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) return;
        String picPath = data.getExtras().getString("result");
        int position = data.getExtras().getInt("position");
        switch (requestCode) {
            case CameraView.CAMERA_IMAGE:
            case FillModeRcAdapterNew.REQUEST_TAKEPHOTO:

                if (!TextUtils.isEmpty(picPath)) {
                    Picture pic = new Picture();
                    pic.setFilePath(picPath);
                    pic.setGuid(UUID.randomUUID().toString());
                    pic.setRelateType(4);//拜访照片
                    pic.setFillName(picPath.substring(picPath.lastIndexOf("/") + 1));
                    pic.setProcessCode(code);
                    pic.setIsUpload(0);
                    pic.setVisitGuid(workGuid);
                    PictureUtils.insertPicture(pic);
                    inspectTemplate.getItems().get(position).setFillName(inspectTemplate.getItems().get(position).getFillName() + (inspectTemplate.getItems().get(position).getFillName().length() > 0 ? "|" + pic.getGuid() : pic.getGuid()));
                    inspectTemplate.getItems().get(position).setFillValue(inspectTemplate.getItems().get(position).getFillName());
                    fillModeRcAdapter.notifyDataSetChanged();
                }
                break;
        }
    }
}
